<template>
  <view class="container">
    <view class="header">
      <text class="title">RSA分段加密解密演示</text>
    </view>

    <view class="section">
      <text class="section-title">1. 密钥管理</text>
      <button @click="generateKeys" :disabled="loading" class="btn">
        {{ loading ? '生成中...' : '生成密钥对' }}
      </button>
      
      <view v-if="keys.publicKey" class="key-info">
        <text class="key-label">公钥:</text>
        <text class="key-text">{{ keys.publicKey.substring(0, 50) }}...</text>
        <text class="key-label">私钥:</text>
        <text class="key-text">{{ keys.privateKey.substring(0, 50) }}...</text>
        <text class="key-status" :class="{ 'valid': keyValid, 'invalid': !keyValid }">
          {{ keyValid ? '✓ 密钥对有效' : '✗ 密钥对无效' }}
        </text>
      </view>
    </view>

    <view class="section">
      <text class="section-title">2. 数据加密解密</text>
      <textarea 
        v-model="inputData" 
        placeholder="请输入要加密的数据"
        class="input-area"
      />
      <button @click="encryptData" :disabled="loading" class="btn">
        加密数据
      </button>
      
      <view v-if="encryptedResult" class="result">
        <text class="result-label">加密结果:</text>
        <text class="result-text">{{ encryptedResult.substring(0, 100) }}...</text>
        <text class="result-info">段数: {{ getEncryptionInfo().totalSegments }}</text>
      </view>
    </view>

    <view class="section">
      <text class="section-title">3. 数据解密</text>
      <button @click="decryptData" :disabled="!encryptedResult || loading" class="btn">
        解密数据
      </button>
      
      <view v-if="decryptedResult" class="result">
        <text class="result-label">解密结果:</text>
        <text class="result-text">{{ decryptedResult }}</text>
      </view>
    </view>

    <view class="section">
      <text class="section-title">4. 验证结果</text>
      <view v-if="decryptedResult" class="verification">
        <text class="verification-text" :class="{ 'success': isVerified, 'error': !isVerified }">
          {{ isVerified ? '✓ 加密解密成功！' : '✗ 加密解密失败！' }}
        </text>
      </view>
    </view>

    <view class="section">
      <text class="section-title">5. 测试功能</text>
      <button @click="testChinese" :disabled="loading" class="btn">
        测试中文加密
      </button>
      <button @click="testLargeData" :disabled="loading" class="btn">
        测试大数据加密
      </button>
      <button @click="testSpecialChars" :disabled="loading" class="btn">
        测试特殊字符
      </button>
      <button @click="clearAll" class="btn btn-clear">
        清除所有数据
      </button>
    </view>

    <view class="section">
      <text class="section-title">6. 性能信息</text>
      <view class="performance-info">
        <text class="perf-text">最大加密长度: {{ rsaCrypto.maxEncryptSize }} 字符</text>
        <text class="perf-text">密钥长度: {{ rsaCrypto.keySize }} 位</text>
        <text v-if="encryptTime" class="perf-text">加密耗时: {{ encryptTime }}ms</text>
        <text v-if="decryptTime" class="perf-text">解密耗时: {{ decryptTime }}ms</text>
      </view>
    </view>
  </view>
</template>

<script>
import RSASegmentCrypto from '@/utils/rsa-segment-crypto.js'
import RSA from '@/utils/crypto.js'

export default {
  data() {
    return {
      rsaCrypto: null,
      keys: {
        publicKey: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqYDnNgGpi8s5FR3d9ASco08WZFd5HNE+oAYFgr5nFRNPScV0DqXLU9oM+eeW0cyRmnh+WfrCUL2cUopwns4wv0O9lM93Ljaiskfjrwrrred7G82AAt6UfQNmheOcrQrKLU8znzDQ3N8cO6cD1CbuWgKB2JlndxotJFhO5OK4avwIDAQAB',
        privateKey: 'MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKpgOc2AamLyzkVHd30BJyjTxZkV3kc0T6gBgWCvmcVE09JxXQOpctT2gz555bRzJGaeH5Z+sJQvZxSinCezjC/Q72Uz3cuNqKyR+OvCuut53sbzYAC3pR9A2aF45ytCsotTzOfMNDc3xw7pwPUJu5aAoHYmWd3Gi0kWE7k4rhq/AgMBAAECgYAWEijFcYfBRraoQeBS7hXOaP9VhqreAC2mKX/C8IHpN10rYKp4gXh8lGyfE3fJfwsC93lHFnq1z52OY5xQBlHitCIbVfsFg0oi3AV6IzM8/rWc44XYiIUkABlhf/tEMeflzMjnNCfJ0pLiJVyiz6nE4IOM90jWORiZSozvTzjleQJBAK0soTbh2thC986hszj5xoWQ2kZzW9rL6keCNw3PBZ2pCutuSi8g81htE7jenP43gptZDg++HutQ2TFpXzb/5ucCQQD73PR7mU7Dgn+Xn2yVRZvXiNT0m5bQqoiMPm91Sc4NkTPBqJ5Gcusb7yPV9lNaImDjvkc17dBMGqDZKj9tJappAkATOTAQMpQji5OMmYCWo4t5CjJgva+Fozs3gunvm3qJHNm8drq/bo300+7rh7KvuaPC8OjRsI4oGwpxJLxQE6ojAkEAtXJTN5AU7Ejhfuw9n7SMN1S+hpJorl+NC+wXBBpttdx7uvKtQ/eaZX99A7H4DqFhx/DXAIUZYRp18r26//j4sQJACSoqJWa8cNhmF7+TPK6OmKmLzdQ+X91AWosT5YIld2N4Ri7yVlzo8/9rRtP82b7Xk5OdlxVPNIAEXWEeAs7nag=='
      },
      inputData: '',
      encryptedResult: '',
      decryptedResult: '',
      loading: false,
      keyValid: false,
      encryptTime: 0,
      decryptTime: 0
    }
  },

  computed: {
    isVerified() {
      return this.inputData && this.decryptedResult && 
             this.inputData === this.decryptedResult;
    }
  },

  onLoad() {
    this.rsaCrypto = new RSASegmentCrypto(1024);
	this.rsa = new RSA();
    this.loadKeysFromStorage();
  },

  methods: {
    async generateKeys() {
      this.loading = true;
      try {
        this.keys = await this.rsaCrypto.generateKeyPair();
        this.keyValid = this.rsaCrypto.testKeyPair(this.keys.publicKey, this.keys.privateKey);
        this.saveKeysToStorage();
        uni.showToast({
          title: '密钥生成成功',
          icon: 'success'
        });
      } catch (error) {
        uni.showToast({
          title: '密钥生成失败',
          icon: 'error'
        });
        console.error('密钥生成失败:', error);
      } finally {
        this.loading = false;
      }
    },

    async encryptData() {
      if (!this.inputData.trim()) {
        uni.showToast({
          title: '请输入要加密的数据',
          icon: 'none'
        });
        return;
      }

      this.loading = true;
      const startTime = Date.now();
      
      try {
        this.encryptedResult = this.rsa.signWithPrivateKey(
          this.inputData, 
          this.keys.privateKey
        );
        this.encryptTime = Date.now() - startTime;
        console.log(this.encryptedResult)
        uni.showToast({
          title: '加密成功',
          icon: 'success'
        });
      } catch (error) {
        uni.showToast({
          title: '加密失败',
          icon: 'error'
        });
        console.error('加密失败:', error);
      } finally {
        this.loading = false;
      }
    },

    async decryptData() {
      this.loading = true;
      const startTime = Date.now();
      
      try {
        this.decryptedResult = this.rsa.verifyWithPublicKey(
          this.encryptedResult, 
          this.keys.publicKey
        );
        this.decryptTime = Date.now() - startTime;
        uni.showToast({
          title: '解密成功',
          icon: 'success'
        });
      } catch (error) {
        uni.showToast({
          title: '解密失败',
          icon: 'error'
        });
        console.error('解密失败:', error);
      } finally {
        this.loading = false;
      }
    },

    async testChinese() {
      this.inputData = '你好，世界！这是一个中文测试消息。' + 
                      'RSA加密算法可以很好地处理中文字符。' +
                      '这个消息比较长，需要分段处理。' +
                      '支持各种中文字符：中文、英文、数字123、符号！@#￥%……&*（）';
      uni.showToast({
        title: '已设置中文测试数据',
        icon: 'success'
      });
    },

    async testLargeData() {
      // 生成大数据进行测试
      const largeData = 'A'.repeat(200) + 'B'.repeat(200) + 'C'.repeat(200) + 
                       'D'.repeat(200) + 'E'.repeat(200);
      this.inputData = largeData;
      uni.showToast({
        title: '已设置大数据测试',
        icon: 'success'
      });
    },

    async testSpecialChars() {
      this.inputData = '特殊字符测试：!@#$%^&*()_+-=[]{}|;:,.<>?`~' + 
                      '换行符\n制表符\t' +
                      'Unicode字符：🎉🚀💻' +
                      '数字：1234567890' +
                      '空格测试    多个空格';
      uni.showToast({
        title: '已设置特殊字符测试',
        icon: 'success'
      });
    },

    getEncryptionInfo() {
      if (!this.encryptedResult) return {};
      try {
        return this.rsaCrypto.getEncryptionInfo(this.encryptedResult);
      } catch (error) {
        return {};
      }
    },

    saveKeysToStorage() {
      try {
        this.rsaCrypto.saveKeyToStorage(this.keys.publicKey, 'rsa_public_key');
        this.rsaCrypto.saveKeyToStorage(this.keys.privateKey, 'rsa_private_key');
      } catch (error) {
        console.error('保存密钥失败:', error);
      }
    },

    loadKeysFromStorage() {
      try {
        const publicKey = this.rsaCrypto.loadKeyFromStorage('rsa_public_key');
        const privateKey = this.rsaCrypto.loadKeyFromStorage('rsa_private_key');
        
        if (publicKey && privateKey) {
          this.keys = { publicKey, privateKey };
          this.keyValid = this.rsaCrypto.testKeyPair(publicKey, privateKey);
        }
      } catch (error) {
        console.error('加载密钥失败:', error);
      }
    },

    clearAll() {
      this.inputData = '';
      this.encryptedResult = '';
      this.decryptedResult = '';
      this.keys = { publicKey: '', privateKey: '' };
      this.keyValid = false;
      this.encryptTime = 0;
      this.decryptTime = 0;
      
      // 清除存储的密钥
      try {
        uni.removeStorageSync('rsa_public_key');
        uni.removeStorageSync('rsa_private_key');
      } catch (error) {
        console.error('清除存储失败:', error);
      }
      
      uni.showToast({
        title: '数据已清除',
        icon: 'success'
      });
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.btn {
  background-color: #007aff;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx 40rpx;
  margin: 10rpx 0;
  font-size: 28rpx;
}

.btn:disabled {
  background-color: #ccc;
}

.btn-clear {
  background-color: #ff3b30;
}

.key-info {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
}

.key-label {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-top: 10rpx;
}

.key-text {
  font-size: 24rpx;
  color: #333;
  word-break: break-all;
  display: block;
  margin-bottom: 10rpx;
}

.key-status {
  font-size: 24rpx;
  font-weight: bold;
  display: block;
  margin-top: 10rpx;
}

.key-status.valid {
  color: #28a745;
}

.key-status.invalid {
  color: #dc3545;
}

.input-area {
  width: 100%;
  height: 500rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  margin-bottom: 20rpx;
  box-sizing: border-box;
}

.result {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
}

.result-label {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.result-text {
  font-size: 24rpx;
  color: #333;
  word-break: break-all;
  display: block;
  margin-bottom: 10rpx;
}

.result-info {
  font-size: 20rpx;
  color: #999;
  display: block;
}

.verification {
  text-align: center;
  padding: 20rpx;
}

.verification-text {
  font-size: 32rpx;
  font-weight: bold;
}

.verification-text.success {
  color: #28a745;
}

.verification-text.error {
  color: #dc3545;
}

.performance-info {
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
}

.perf-text {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}
</style> 